package com.trace.demo.controller;

import com.trace.demo.entity.Customer;
import com.trace.demo.entity.User;
import com.trace.demo.repository.CustomerRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/customers")
public class CustomerController {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Customer>>> getAllCustomers() {
        List<Customer> customers = customerRepository.findAll();
        return ResponseEntity.ok(new ApiResponse<>(true, "Customers retrieved successfully", customers));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Customer>> getCustomerById(@PathVariable Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        return customer.map(value -> ResponseEntity.ok(new ApiResponse<>(true, "Customer retrieved successfully", value)))
                .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "Customer not found with id: " + id, null)));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Customer>> addCustomer(@RequestBody Customer customer, @RequestParam(required = false) Long userId) {
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            if (userOptional.isPresent()) {
                customer.setUser(userOptional.get());
            }
        }

        Customer savedCustomer = customerRepository.save(customer);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(new ApiResponse<>(true, "Customer added successfully", savedCustomer));
    }

    @PutMapping
    public ResponseEntity<ApiResponse<Customer>> updateCustomer(@RequestBody Customer customer) {
        Optional<Customer> existingCustomer = customerRepository.findById(customer.getId());
        if (!existingCustomer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Customer not found with id: " + customer.getId(), null));
        }

        customer.setCreatedAt(existingCustomer.get().getCreatedAt());
        if (existingCustomer.get().getUser() != null) {
            customer.setUser(existingCustomer.get().getUser());
        }

        Customer updatedCustomer = customerRepository.save(customer);
        return ResponseEntity.ok(new ApiResponse<>(true, "Customer updated successfully", updatedCustomer));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteCustomer(@PathVariable Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        if (!customer.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Customer not found with id: " + id, null));
        }

        customerRepository.deleteById(id);
        return ResponseEntity.ok(new ApiResponse<>(true, "Customer deleted successfully", null));
    }
}
